var DROPMENU_MODE_BOTTOM = 0;
var DROPMENU_MODE_RIGHT = 1;

function DropMenu(element, mode) {
  if (element != null && mode != null) {
    var pos = util.findPos(element);
    this.x = pos[0] + ((mode == DROPMENU_MODE_RIGHT) ? element.offsetWidth : 0);
    this.y = pos[1] + ((mode == DROPMENU_MODE_BOTTOM) ? element.offsetHeight : 0);
  }
  this.items = [];
  this.containerDiv = null;
  this.mouseDownHandler = this.mouseDownHandler.bind(this);
  this.resizeHandler = this.resizeHandler.bind(this);
  
  this.cssClass = 'dropmenu-container';
  this.cssClassItem = 'dropmenu-item';
  this.cssClassItemHighlight = 'dropmenu-item-highlight';
  this.cssClassComment = 'dropmenu-comment';
  this.cssClassLink = 'dropmenu-link';
}

DropMenu.prototype.mouseDownHandler = function () {
  if (!this.underMouse) {
    this.close();
  }
};

DropMenu.prototype.resizeHandler = function () {
  this.close();
};

DropMenu.prototype.setCoords = function (x, y) {
  this.x = x;
  this.y = y;
};

DropMenu.prototype.addItem = function(text, opt_link) {
  this.items.push(new DropMenuItem(text, opt_link));
};

DropMenu.prototype.draw = function() {
  if (this.x == null || this.y == null) {
    throw 'Coordinates have not been set';
  }
  this.containerDiv = document.createElement('div');
  this.containerDiv.className = this.cssClass;
  this.containerDiv.style.left = this.x + 'px';
  this.containerDiv.style.top = this.y + 'px';

  for (var i = 0; i < this.items.length; i++) {
    var item = this.items[i];
    var div = this.getItemDiv(item);
    this.containerDiv.appendChild(div);
  }
  util.addEvent(document, 'mousedown', this.mouseDownHandler);
  util.addEvent(window, 'resize', this.resizeHandler);
  var body = document.getElementsByTagName("body").item(0);
  body.appendChild(this.containerDiv);
};

DropMenu.prototype.close = function() {
  try {
    this.containerDiv.parentNode.removeChild(this.containerDiv);
  } catch (e) {}
  util.removeEvent(document, 'mousedown', this.mouseDownHandler);
  util.removeEvent(window, 'resize', this.resizeHandler);
};

DropMenu.prototype.getItemDiv = function(item) {
  var self = this;
  var div = document.createElement('div');
  div.className = this.cssClassItem;
  div.onmouseover = function() {
    this.className = self.cssClassItemHighlight;
    self.underMouse = true;
  }
  div.onmouseout = function() {
    this.className = self.cssClassItem;
    self.underMouse = false;
  }
  div.onclick = function() {
    self.close();
    window.location = item.link;
  }
  div.style.cursor = 'pointer';
  link = document.createElement('a');
  link.href = item.link;
  link.onclick = function() {
    self.close();
    window.location = this.href;
  }
  link.className = this.cssClassLink;
  link.innerHTML = item.text;
  div.appendChild(link);
  return div;
};

function DropMenuItem(text, link) {
  this.text = text;
  this.link = link;
}